package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.*;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private CheckGroupDao checkGroupDao;
    @Autowired
    private InterventionDao interventionDao;
    @Autowired
    private FoodDao foodDao;
    @Autowired
    private SportDao sportDao;

    //根据手机号查找会员信息
    @Override
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    //保存会员信息
    @Override
    public void add(Member member) throws Exception {
        String password = member.getPassword();
        if (password != null) {
            //使用md5将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        member.setRegTime(new Date());
        Date birthday = member.getBirthday();
        if (birthday != null) {
            int age = DateUtils.getAgeByBirth(birthday);
            member.setAge(age);
        }
        memberDao.add(member);
    }

    //根据月份统计会员数量
    @Override
    public List<Integer> findMemberCountByMonth(List<String> month) {
        List<Integer> list = new ArrayList<>();
        for (String m : month) {
            m = m + ".31";//格式：2020.09.31
            Integer count = memberDao.findMemberCountBeforeDate(m);
            list.add(count);
        }
        return list;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //查询条件
        String queryString = queryPageBean.getQueryString();
        //当前页数
        Integer currentPage = queryPageBean.getCurrentPage();
        //总页数
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page page = memberDao.findByCondition(queryString);
        //总页数
        long total = page.getTotal();
        //当前页结果
        List<Member> result = page.getResult();

        for (Member member : result) {
            User userCopy = new User();
            User user = userDao.findById(member.getUser_Id());
            if (user != null) {
                String username = user.getUsername();
                Integer id = user.getId();
                userCopy.setUsername(username);
                userCopy.setId(id);
                member.setUser(userCopy);
            }
        }
        return new PageResult(total, result);
    }

    //id查找会员
    @Override
    public Member findById(String id) {
        Member member = memberDao.findById(Integer.parseInt(id));
        User user = userDao.findById(member.getUser_Id());
        member.setUser(user);
        return member;
    }

    @Override
    public void edit(Member member) {
        Date birthday = member.getBirthday();
        if (birthday != null) {
            int age = DateUtils.getAgeByBirth(birthday);
            member.setAge(age);
        }
        memberDao.edit(member);
    }

    @Override
    public void deleteById(String id) {
        Long count = orderDao.findCountIdByMemberId(Integer.valueOf(id));
        if (count>0){
            throw new RuntimeException("该会员信息与"+count+"条预约信息关联，删除关联信息后重试");
        }else{
            memberDao.deleteById(Integer.valueOf(id));
        }
    }


    @Override
    public List<Map> getMemberData(List<Member> memberList) {
        List<Map> list = new ArrayList<>();
        //遍历会员集合
        for (Member member : memberList) {
            //获得单个会员所有的预约信息id
            List<Integer> memberIds = orderDao.findCheckGroupByMemberId(member.getId());
            //遍历预约信息id
            for (Integer integer : memberIds) {
                Map<String, Object> map = new HashMap<>();
                String name = member.getName();
                String sex = member.getSex();
                sex = sex.equals("1") ? "男" : "女";
                String phoneNumber = member.getPhoneNumber();
                //查询会员检查套餐相对机构的的地址
                String address = addressDao.findAddressByOrderId(integer);
                //获得预约信息对应的套餐对象
                Setmeal setmeal = setmealDao.findSetmealNameDaoByOrderId(integer);
                //套餐名
                String setmealName = setmeal.getName();
                //获得检查组
                List<CheckGroup> checkGroupList = checkGroupDao.findCheckGroupById(setmeal.getId());

                //检查组名字集合
                /*List<String> checkGroupNames = new ArrayList<>();*/
                StringBuilder checkGroupNames = new StringBuilder();
                StringBuilder checkItemNames = new StringBuilder();
                //检查项名字集合
                /*List<String> checkItemNames = new ArrayList<>();*/
                for (CheckGroup checkGroup : checkGroupList) {
                    checkGroupNames.append(checkGroup.getName() + " ");
                    List<CheckItem> checkItems = checkGroup.getCheckItems();
                    for (CheckItem checkItem : checkItems) {
                        checkItemNames.append(checkItem.getName() + " ");
                    }
                }
                String checkGroupNamess = checkGroupNames.toString();
                String checkItemNamess = checkItemNames.toString();
                map.put("name", name);
                map.put("sex", sex);
                map.put("phoneNumber", phoneNumber);
                map.put("address", address);
                map.put("setmealName", setmealName);
                map.put("checkGroupNamess", checkGroupNamess);
                map.put("checkItemNamess", checkItemNamess);
                list.add(map);
            }
        }
        return list;
    }

    //根据月份查询会员数量
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCounts = new ArrayList<>();
        if(months != null && months.size() > 0){
            for (String month : months) {//2019.01
                String endTime = month + ".31";
                Integer memberCount = memberDao.findMemberCountBeforeDate(endTime);
                memberCounts.add(memberCount);
            }
        }
        return memberCounts;
    }

    @Override
    public List<Map> getsetmealListByPhoneNumber(String phoneNumber) {
        List<Map> list = memberDao.getsetmealListByPhoneNumber(phoneNumber);
        for (Map map : list) {
            String orderStatus = (String) map.get("orderStatus");
            if ("已到诊".equals(orderStatus)){
                //获取订单id
                Integer id = (Integer) map.get("id");
                //根据订单id查询一个健康干预
                Intervention intervention = interventionDao.findByOrderId(id);
                if (intervention!=null){
                    Integer interventionId = intervention.getId();
                    //根据健康干预id查询膳食建议
                    List<Food> foods = foodDao.findFoodsByInterventionId(interventionId);
                    intervention.setFoods(foods);
                    //根据健康干预id查询运动建议
                    List<Sport> sports = sportDao.findSportsByInterventionId(interventionId);
                    intervention.setSports(sports);
                    //添加到map中
                    map.put("doctorName",intervention.getDoctorName());
                    map.put("doctorAdvice",intervention.getDoctorAdvice());
                    StringBuilder foodAdvice = new StringBuilder();
                    if (foods!=null&&foods.size()>0){
                        for (Food food : foods) {
                            foodAdvice.append(food.getName()).append(" ");
                        }
                    }
                    StringBuilder sportAdvice = new StringBuilder();
                    if (sports!=null&&sports.size()>0){
                        for (Sport sport : sports) {
                            sportAdvice.append(sport.getName()).append(" ").append(sport.getSize()).append(" ").append(sport.getRuntime()).append("\n");
                        }
                    }
                    map.put("foods",foodAdvice.toString());
                    map.put("sports",sportAdvice.toString());
                }
            }
        }
        return list;
    }
}
